package com.shao.Dao.impl;

import com.shao.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: SJP
 * Date: 2021/5/11
 * Time: 20:28
 * Description: No Description
 */
public abstract class BaseDao {

    //使用Dbutils工具类来操作数据库（包含QueryRunner类和ResultSetHandler类）
    private QueryRunner queryRunner = new QueryRunner();

    /**
     * update()方法用来执行update/delete/insert语句
     * @param sql  语句
     * @param args 参数值
     * @return  表示受影响行数，如果返回-1则执行失败
     */
    public int update(String sql, Object...args){
        Connection connection = JdbcUtils.getConnection();
        try {
            return queryRunner.update(connection,sql,args);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.Close(connection);
        }
        return -1;
    }

    /**
     * 查询语句返回一个javabean
     * @param type 返回对象的类型
     * @param sql 执行的查询语句
     * @param args sql对应的参数
     * @param <T> 返回类型的泛型
     * @return
     */
    public <T>T QueryForOne(Class<T>type,String sql,Object...args){
        Connection connection = JdbcUtils.getConnection();
        try {
            return queryRunner.query(connection,sql,new BeanHandler<T>(type),args);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.Close(connection);
        }
        return null;
    }
    public <T> List<T> QueryMore(Class<T>type, String sql, Object...args){
        Connection connection = JdbcUtils.getConnection();
        try {
            return queryRunner.query(connection,sql,new BeanListHandler<T>(type),args);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.Close(connection);
        }
        return null;
    }
    public Object queryForSingleValue(String sql, Object... args){
        Connection conn = JdbcUtils.getConnection();
        try {
            return queryRunner.query(conn, sql, new ScalarHandler(), args);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.Close(conn);
        }
        return null;
    }
}
